package com.sx.gongzhong.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.activity.HelpDetailActivity;
import com.sx.gongzhong.activity.LoginActivity;
import com.sx.gongzhong.model.CommentBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PublicBean;
import com.sx.gongzhong.model.PublicTotalBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.AdoptPest;
import com.sx.gongzhong.pest.DeletePest;
import com.sx.gongzhong.pest.ReportAndForbiddenPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.InitData;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.widget.CustomDialog;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.ReportDialog;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**  评论列表
 *   举报模块类型对照表
     中文名	              编号
     便民诉求评论	         convenient_appeal_comment
     爆料回复	         broke_news_reply
     互帮互助	         help_each_other
     互帮互助回复	         help_each_other_reply
     全民护路	         national_road_protection
     法律咨询	         legal_advice
 * Created by XZY on 2017/12/28
 *
 */

public class CommentListAdapter extends BaseQuickAdapter<CommentBean,BaseViewHolder> {

    private String publishUserId = "";//发布帖子人的id
    private Context context;
    private String columnType;//模块类型
    private boolean isHost = false;//是否发布人 用于显示采纳
    private boolean isVisiAdopt = false;//仅待解决 显示采纳
    public void setPublishUserId(String publishUserId) {
        this.publishUserId = publishUserId;
    }
    public void setHost(boolean host) {
        isHost = host;
    }

    public void setVisiAdopt(boolean visiAdopt) {
        isVisiAdopt = visiAdopt;
    }

    public void setColumnType(String columnType) {
        this.columnType = columnType;
    }

    public CommentListAdapter(Context context, @LayoutRes int layoutResId, @Nullable List<CommentBean> data) {
        super(layoutResId, data);
        this.context=context;
    }
    @Override
    protected void convert(BaseViewHolder helper, CommentBean item) {
        helper.setText(R.id.tv_Time,BaseUtil.isEmpty(item.commentTime) ? item.replyTime : item.commentTime);
        helper.setText(R.id.tv_Content,item.content);
        if (item.replyUser != null){
            item.commentUser = item.replyUser;
        }
        if (item.commentUser != null){
            helper.setText(R.id.tv_Name,item.commentUser.getName());
            ImageView iv_headerUrl = helper.getView(R.id.im_Head);
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.img_head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.img_head_default);
            Glide.with(context)
                    .load(ServiceFactory.getUrl( item.commentUser.getHeaderUrl()))
                    .apply(options)
                    .into(iv_headerUrl);
        }
        TextView shutup = helper.getView(R.id.tv_ShutUp);
        TextView report = helper.getView(R.id.tv_Report);
        TextView delete = helper.getView(R.id.tv_Delete);
        TextView Adopt = helper.getView(R.id.tv_Adopt);

        shutup.setOnClickListener(new MyClickListener(item));
        report.setOnClickListener(new MyClickListener(item));
        delete.setOnClickListener(new MyClickListener(item));
        Adopt.setOnClickListener(new MyClickListener(item));

        if (MyApplication.instance.userBean!=null) {
            if ("general".equalsIgnoreCase(MyApplication.instance.userBean.userType.code)) {//普通用户
                shutup.setVisibility(View.GONE);
                if (item.commentUser != null){
                    if (!item.commentUser.getId().equals(MyApplication.instance.userBean.id)) {
                        delete.setVisibility(View.GONE);
                    } else {
                        delete.setVisibility(View.VISIBLE);
                    }
                } else {
                    delete.setVisibility(View.VISIBLE);
                }

            }
            if (columnType.equals("help_each_other_reply")){//互帮互助有采纳
                if (isHost && isVisiAdopt){
                    Adopt.setVisibility(View.VISIBLE);
                }
            }
        }
    }

   private class MyClickListener implements View.OnClickListener{
        private CommentBean commentBean;
        private MyClickListener(CommentBean commentBean) {
            this.commentBean=commentBean;
        }
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tv_Adopt://采纳
                    createDialog("采纳",1);
                    break;
                case R.id.tv_ShutUp://整个诉求禁言
                    createDialog("禁言",2);
                    break;
                case R.id.tv_Report://举报楼主
                    createDialog("举报",3);
                    break;
                case R.id.tv_Delete:
                    createDialog("删除",4);
                    break;
            }
        }
       // 删除/举报/禁言/采纳
       public void createDialog(String str, final int type) {
           if (MyApplication.instance.userBean == null || BaseUtil.isEmpty(MyApplication.instance.userBean.sid)){
               initRx();
               context.startActivity(new Intent(context, LoginActivity.class));
           }else {
               CustomDialog dialog = new CustomDialog.Builder(context)
                       .setMessage("确定" + str + "吗？").
                       setBackButton("取消", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.dismiss();
                           }
                       }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       dialog.dismiss();
                       if (type == 1){
                           adopt();
                       }else if (type == 2){
                           createReport("forbiddenType");
                       }else if (type == 3){
                           createReport("reportType");
                       }else if (type == 4){
                           LoadDialog.show(context,"删除中...");
                           deleteCommon();
                       }
                   }
               }).create();
               dialog.show();
           }
       }

       private void adopt() {
           new AdoptPest(new IVoidView() {
               @Override
               public void voidView(String re) {
                   ((HelpDetailActivity)context).adpotSuccess();
                   LoadDialog.dismiss(context);
                   ToastUtils.showToast(context,"采纳成功");
               }
               @Override
               public void showError(String message) {
                   ToastUtils.showToast(context,message);
               }
           }).adoptCommon(commentBean.id);
       }

       private void deleteCommon() {
           String url = "";
           switch (columnType){
               case "convenient_appeal_comment": // 便民诉求评论
                   url = "/api/columnManage/convenientAppeal/deleteCommentById";
                   break;
               case "broke_news_reply":// 爆料回复
                   url = "/api/columnManage/brokeNews/deleteReplyById";
                   break;
               case "help_each_other_reply"://互帮互助
                   url ="/api/columnManage/helpEachOther/deleteReplyById";
                   break;
           }
           new DeletePest(new IVoidView() {
               @Override
               public void voidView(String re) {
                   LoadDialog.dismiss(context);
                   getData().remove(commentBean);
                   notifyDataSetChanged();
                   ToastUtils.showToast(context,"删除成功");
               }
               @Override
               public void showError(String message) {
                   LoadDialog.dismiss(context);
                   ToastUtils.showToast(context,message);
               }
           }).deleteCommon(url,commentBean.id);
       }

       /**
        * @param type 禁言 举报
        */
       private void createReport(final String type) {
           PublicTotalBean bean = DataStorageFactory.getInstance(context,
                   DataStorageFactory.TYPE_DATABASE).load(PublicTotalBean.class,type);
           //获取到举报类型
           if (bean != null && bean.getChildren()!=null){
               ReportDialog.Builder builder=new ReportDialog.Builder(context);
               String title = "选择禁言时间";
               if ("reportType".equals(type)){
                   title = "选择举报类型";
               }
               builder.setDataList(bean.getChildren()).setTitle(title)
                       .loadType(new ReportDialog.TypeCallback() {
                           @Override
                           public void backType(PublicBean publicBean) {
                               if ("reportType".equals(type)) {//举报
                                   new ReportAndForbiddenPest(new IVoidView() {
                                       @Override
                                       public void voidView(String string) {//举报成功
                                           ToastUtils.showToast(context,string);
                                       }
                                       @Override
                                       public void showError(String message) {
                                           ToastUtils.showToast(context,message);
                                       }
                                   }).report(publicBean.getId(), columnType, commentBean.id);
                               }
                               if ("forbiddenType".equals(type)) {//禁言
                                   new ReportAndForbiddenPest(new IVoidView() {
                                       @Override
                                       public void voidView(String string) { //禁言成功
                                           ToastUtils.showToast(context,string);
                                       }
                                       @Override
                                       public void showError(String message) {
                                           ToastUtils.showToast(context,message);
                                       }
                                   }).addForbidden(publicBean.getId(),columnType, commentBean.id);
                               }
                           }
                       }).create().show();
           }else {
               new InitData(context).loadData();
               ToastUtils.showToast(context,"服务器异常 稍后再试");
           }
       }
    }
    private Disposable disposable;
    private void initRx() {
        disposable =  MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        if ("CommentListAdapter".equals(msgEvent.getRequest())) {
                            if (MyApplication.instance.userBean != null){
                                if (MyApplication.instance.userBean.id.equals(publishUserId)){
                                    isHost = true;
                                }
                            }
                            notifyDataSetChanged();
                            disposable = null;
                        }
                    }
                });
    }
}
